#include "Dictionary.h"

Dictionary *Dictionary::_instance = nullptr;

Dictionary *Dictionary::getInstance() {
    if (!_instance) {
        _instance = new Dictionary();
    }
    return _instance;
}

void Dictionary::delInstance() {
    if (_instance) {
        delete _instance;
        _instance = nullptr;
    }
}

Dictionary::Dictionary() {}

Dictionary::~Dictionary() {}

void Dictionary::init(const string &dictPath) {
    // 路径为/home/kyle/Project/WebDisk/data
    // 加载字典文件
    loadDictionary(dictPath + "/dict_eng.dat", _eng_dict); // 加载英文字典
    loadDictionary(dictPath + "/dict_chs.dat", _chs_dict); // 加载中文字典

    // 加载索引文件
    loadIndexTable(dictPath + "/dict_eng_index.dat", _eng_indexTable); // 加载英文索引
    loadIndexTable(dictPath + "/dict_chs_index.dat", _chs_indexTable); // 加载中文索引
}

void Dictionary::loadDictionary(const string &dictFile, vector<pair<string, int>> &dict) {
    std::ifstream ifs(dictFile);
    if (!ifs.is_open()) {
        std::cerr << "Failed to open dictionary file: " << dictFile << std::endl;
        return;
    }

    string line;
    while (std::getline(ifs, line)) {
        std::stringstream ss(line);
        string word;
        int index;
        ss >> word >> index;
        dict.push_back({word, index});
    }

    ifs.close();
}

void Dictionary::loadIndexTable(const string &indexFile, map<string, set<int>> &indexTable) {
    std::ifstream ifs(indexFile);
    if (!ifs.is_open()) {
        std::cerr << "Failed to open index file: " << indexFile << std::endl;
        return;
    }

    string line;
    while (std::getline(ifs, line)) {
        std::stringstream ss(line);
        string word;
        int index;
        ss >> word;
        while (ss >> index) {
            indexTable[word].insert(index);
        }
    }

    ifs.close();
}

vector<pair<string, int>> &Dictionary::getEngDict() {
    return _eng_dict;
}

vector<pair<string, int>> &Dictionary::getChsDict() {
    return _chs_dict;
}

map<string, set<int>> &Dictionary::getEngIndexTable() {
    return _eng_indexTable;
}

map<string, set<int>> &Dictionary::getChsIndexTable() {
    return _chs_indexTable;
}